import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { BaseListResultModel } from 'src/logical/common/models/BaseListResult.model';
import { Pagination } from 'src/logical/common/models/Pagination.model';
import { BaseService } from 'src/logical/common/services/base.service';
import { LoginLogEntity } from '../entity/loginLog.entity';
import { loginLogDetailModel } from '../models/loginLogDetail.model';

@Injectable()
export class LoginLogService extends BaseService {
  constructor(
    @InjectModel(LoginLogEntity)
    private loginLogEntityModel: typeof LoginLogEntity,
  ) {
    super();
  }

  async saveLoginLog(loginLogEntity) {
    try {
      console.log(loginLogEntity.get());

      await LoginLogEntity.create(loginLogEntity.get());
    } catch (error) {
      console.error(error);
      return this.saveFailedResultData('保存失败');
    }
    return this.saveSuccessResultData();
  }

  async queryForList(
    queryModel,
    pagination,
  ): Promise<BaseListResultModel<Array<loginLogDetailModel>>> {
    let resList: Array<loginLogDetailModel> = new Array();
    let totalCount: number = 0;
    const pag = new Pagination();
    pag.setCurrent(pagination.current);
    pag.setPagesize(pagination.pagesize);
    pag.setTotal(pagination.total);

    resList = await this.loginLogEntityModel.findAll({
      where: queryModel,
      offset: pag.getCurrent() - 1,
      limit: pag.getPagesize(),
      order: [['id', 'Asc']],
      raw: true,
    });

    totalCount = await this.loginLogEntityModel.count();

    pag.setTotal(totalCount);
    return this.querySuccessResultListData(resList, pag);
  }
}
